package org.obm.lmtp.impl;

import java.util.List;

import org.obm.lmtp.backend.IDeliveryAgent;
import org.obm.lmtp.backend.IMailboxValidator;
import org.obm.lmtp.backend.LmtpAddress;
import org.obm.lmtp.backend.LmtpEnvelope;
import org.obm.lmtp.backend.LmtpReply;
import org.obm.mina.Blob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BiggLmtpBackend implements ILmtpBackend {

	private static final Logger logger = LoggerFactory
			.getLogger(BiggLmtpBackend.class);

	private List<IMailboxValidator> validator;
	private List<IDeliveryAgent> agents;

	public BiggLmtpBackend(List<IMailboxValidator> validator,
			List<IDeliveryAgent> agents) {
		this.validator = validator;
		this.agents = agents;
	}

	@Override
	public void deliver(LmtpEnvelope env, Blob blob) {
		logger.info("deliver(" + env + ", blob: " + blob);
		for (IDeliveryAgent agent : agents) {
			agent.deliver(env, blob);
		}

		for (LmtpAddress r : env.getRecipients()) {
			r.setDeliveryStatus(LmtpReply.DELIVERY_OK);
		}
	}

	@Override
	public LmtpReply getAddressStatus(LmtpAddress address) {
		logger.info("addressStatus(" + address + ")");
		LmtpReply rep = LmtpReply.INVALID_RECIPIENT_ADDRESS;
		for (IMailboxValidator val : validator) {
			LmtpReply tmp = val.getAddressStatus(address);
			if (tmp == LmtpReply.RECIPIENT_OK) {
				rep = tmp;
				break;
			}
		}
		return rep;
	}

}
